package com.upstream.link.control
{
	import com.upstream.link.SYS;
	import com.upstream.link.model.GameModel;
	
	import flash.geom.Point;

	public class PathLogic
	{
		private var _dataArr:Array;
		public function PathLogic()
		{
			_dataArr = GameModel.getInstance().rectVoVect;
		}
		public function checkPoint(p1:Point,p2:Point):Boolean{
			if(p1.equals(p2)) return false;
			if(p1.x == p2.x){
				if(checkY(p1,p2)) return true;
			}
			if(p1.y == p2.y){
				if(checkX(p1,p2)) return true;
			}
			return checkXY(p1,p2);
		}
		/**
		 * 检测两个点是否可以连通   ：Y坐标一样，检测X坐标   
		 * @param p1
		 * @param p2
		 * @return 
		 * 
		 */		
		private function checkX(p1:Point,p2:Point,isStrict:Boolean=false):Boolean{
			if(isStrict){
				if(this._dataArr[p1.y][p1.x].type !=0 || this._dataArr[p2.y][p2.x].type !=0 ) return false;
			}
			var min:int = Math.min(p1.x,p2.x) + 1;
			var max:int = Math.max(p1.x,p2.x);
			for(var i:int=min;i<max;i++){
				if(this._dataArr[p1.y][i].type != 0) return false;
			}
			
			return true;
		}
		/**
		 *X坐标一样，检测Y坐标 
		 * @param p1
		 * @param p2
		 * @return 
		 * 
		 */	
		private function checkY(p1:Point,p2:Point,isStrict:Boolean=false):Boolean{
			if(isStrict){
				if(this._dataArr[p1.y][p1.x].type !=0 || this._dataArr[p2.y][p2.x].type !=0 ) return false;
			}
			var min:int = Math.min(p1.y,p2.y) + 1;
			var max:int = Math.max(p1.y,p2.y);
			for(var i:int=min;i<max;i++){
				if(this._dataArr[i][p1.x].type != 0) return false;
			}
			return true;
		}
		private function checkXY(p1:Point,p2:Point):Boolean{
			// 判断一个拐点
			if(p1.x != p2.x && p1.y !=p2.y){
				var p12:Point = new Point(p1.x,p2.y);
				var p21:Point = new Point(p2.x,p1.y);
				if((this._dataArr[p21.y][p21.x].type == 0)&&checkX(p1,p21) && checkY(p2,p21) ){
					return true;
				}
				if((this._dataArr[p12.y][p12.x].type == 0)&&checkX(p2,p12) && checkY(p1,p12)){
					return true;
				}
			}
			
			//判断两个拐点
			var xmin:int = Math.min(p1.x,p2.x);
			var xmax:int = Math.max(p1.x,p2.x);
			var ymin:int = Math.min(p1.y,p2.y);
			var ymax:int = Math.max(p1.y,p2.y);
			
			if(ymax != ymin){
				for(var i:int=0;i<SYS.ITEM_X_NUM;i++){
					var t1:Point = new Point(i,ymin);	
					var t2:Point = new Point(i,ymax);
					if(checkTwoPointX(t1,t2)) return true;
				}
			}
			if(xmin != xmax){
				for(var j:int=0;j<SYS.ITEM_Y_NUM;j++){
					var ty1:Point = new Point(xmin,j);	
					var ty2:Point = new Point(xmax,j);
					if(checkTwoPointY(ty1,ty2)) return true;
				}
			}
			return false;
			function checkTwoPointX(pp1:Point,pp2:Point):Boolean{
				return checkX(p1,pp1,false)&&checkY(pp1,pp2,true)&&checkX(p2,pp2,false);
			}
			
			function checkTwoPointY(pp1:Point,pp2:Point):Boolean{
				return checkY(p1,pp1,false)&&checkX(pp1,pp2,true)&&checkY(p2,pp2,false);
			}
		}
	}
}